<template>
  <div class="product-list-container">
    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-group">
          <span class="filter-label">分类:</span>
          <el-select
            v-model="filters.categoryId"
            placeholder="全部分类"
            clearable
            class="filter-select"
            @change="handleFilterChange"
          >
            <el-option
              v-for="category in categories"
              :key="category.typeId"
              :label="category.typeName"
              :value="category.typeId"
            />
          </el-select>
        </div>

        <div class="filter-group">
          <span class="filter-label">品牌:</span>
          <el-select
            v-model="filters.brandId"
            placeholder="全部品牌"
            clearable
            class="filter-select"
            @change="handleFilterChange"
          >
            <el-option
              v-for="brand in brands"
              :key="brand.brand_id"
              :label="brand.brand_name"
              :value="brand.brand_id"
            />
          </el-select>
        </div>

        <div class="filter-group">
          <span class="filter-label">价格:</span>
          <el-select
            v-model="filters.priceRange"
            placeholder="全部价格"
            clearable
            class="filter-select"
            @change="handleFilterChange"
          >
            <el-option label="0-100元" value="0-100" />
            <el-option label="100-300元" value="100-300" />
            <el-option label="300-500元" value="300-500" />
            <el-option label="500-1000元" value="500-1000" />
            <el-option label="1000元以上" value="1000+" />
          </el-select>
        </div>

        <div class="filter-group">
          <span class="filter-label">状态:</span>
          <el-select
            v-model="filters.status"
            placeholder="全部状态"
            clearable
            class="filter-select"
            @change="handleFilterChange"
          >
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </div>

        <div class="filter-group">
          <span class="filter-label">排序:</span>
          <el-select v-model="filters.sortBy" class="filter-select" @change="handleFilterChange">
            <el-option label="综合排序" value="default" />
            <el-option label="价格升序" value="price_asc" />
            <el-option label="价格降序" value="price_desc" />
            <el-option label="销量优先" value="sales" />
            <el-option label="最新上架" value="newest" />
          </el-select>
        </div>
      </div>

      <div class="search-row">
        <el-input
          v-model="filters.keyword"
          placeholder="搜索商品名称、品牌..."
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="products-section">
      <div class="section-header">
        <h1 class="page-title">商品列表</h1>
        <p class="result-count">共 {{ totalCount }} 件商品</p>
      </div>

      <div class="products-grid" v-loading="loading" element-loading-text="加载中...">
        <ProductCard
          v-for="product in products"
          :key="product.productId"
          :product="product"
          @add-to-cart="handleAddToCart"
        />
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && products.length === 0" description="暂无商品" class="empty-state">
        <template #default>
          <el-button type="primary" @click="resetFilters">重置筛选</el-button>
        </template>
      </el-empty>

      <!-- 分页 -->
      <div class="pagination-section" v-if="totalCount > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalCount"
          :page-sizes="[12, 24, 48, 96]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { productService } from '@/api'
import { useCartStore } from '@/stores/cart'
import ProductCard from '@/components/ProductCard.vue'
import type { Shoes, ProductVO, Category, Brand, ProductQuery } from '@/types/product'
import { createLogger } from '@/utils/logger'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const productListLogger = createLogger('ProductList')

// 响应式数据
const products = ref<Shoes[]>([])
const categories = ref<Category[]>([])
const brands = ref<Brand[]>([])
const loading = ref(false)
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const searchKeyword = ref('')

// 筛选条件
const filters = ref({
  categoryId: undefined as number | undefined,
  brandId: undefined as number | undefined,
  priceRange: '',
  status: '1' as string | undefined, // 默认只显示上架商品
  sortBy: 'default',
})

// 计算属性
const queryParams = computed(() => {
  const params: ProductQuery = {
    page: currentPage.value,
    size: pageSize.value,
    keyword: searchKeyword.value || undefined,
  }

  if (filters.value.categoryId) {
    params.typeId = filters.value.categoryId
  }
  if (filters.value.brandId) {
    params.brandId = filters.value.brandId
  }
  if (filters.value.status) {
    params.status = filters.value.status
  }
  if (filters.value.priceRange) {
    const [min, max] = filters.value.priceRange.split('-')
    params.minPrice = min === '1000+' ? 1000 : parseInt(min)
    params.maxPrice = max ? parseInt(max) : undefined
  }

  switch (filters.value.sortBy) {
    case 'price_asc':
      params.sortBy = 'price'
      params.sortOrder = 'asc'
      break
    case 'price_desc':
      params.sortBy = 'price'
      params.sortOrder = 'desc'
      break
    case 'sales':
      params.sortBy = 'sales'
      params.sortOrder = 'desc'
      break
    case 'newest':
      params.sortBy = 'createdTime'
      params.sortOrder = 'desc'
      break
  }

  return params
})

// 加载数据
const loadProducts = async () => {
  loading.value = true
  try {
    let response
    if (searchKeyword.value && searchKeyword.value.trim()) {
      // 如果有搜索关键词，使用搜索API
      const searchOptions = {
        brandId: filters.value.brandId || undefined,
        typeId: filters.value.categoryId || undefined,
        status: filters.value.status || undefined,
        minPrice: queryParams.value.minPrice || undefined,
        maxPrice: queryParams.value.maxPrice || undefined,
        sortBy: queryParams.value.sortBy || undefined,
        sortOrder: queryParams.value.sortOrder || undefined,
      }
      response = await productService.searchProducts(
        searchKeyword.value.trim(),
        currentPage.value,
        pageSize.value,
        searchOptions,
      )
    } else {
      // 否则使用商品列表API
      response = await productService.getProductList(queryParams.value)
    }
    products.value = response.data.data.list
    totalCount.value = response.data.data.total
  } catch (error) {
    productListLogger.error('加载商品列表失败:', error)
    ElMessage.error('加载商品失败')
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const response = await productService.getProductTypes()
    categories.value = response.data.data
  } catch (error) {
    productListLogger.error('加载分类列表失败:', error)
    ElMessage.error('加载分类失败')
  }
}

const loadBrands = async () => {
  try {
    const response = await productService.getProductBrands()
    brands.value = response.data.data
  } catch (error) {
    productListLogger.error('加载品牌列表失败:', error)
    ElMessage.error('加载品牌失败')
  }
}

// 事件处理
const handleFilterChange = () => {
  currentPage.value = 1
  loadProducts()
  updateUrlQuery()
}

const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
  updateUrlQuery()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadProducts()
  updateUrlQuery()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadProducts()
  updateUrlQuery()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleAddToCart = async (product: Product) => {
  const result = await cartStore.addToCart(product.productId, 1)
  if (result.success) {
    ElMessage.success('已添加到购物车')
  } else {
    ElMessage.error(result.error || '添加失败')
  }
}

const resetFilters = () => {
  filters.value = {
    categoryId: undefined,
    brandId: undefined,
    priceRange: '',
    status: '1', // 重置时默认显示上架商品
    sortBy: 'default',
  }
  searchKeyword.value = ''
  currentPage.value = 1
  loadProducts()
  updateUrlQuery()
}

const updateUrlQuery = () => {
  const query: any = {}
  if (filters.value.categoryId) query.category = filters.value.categoryId
  if (filters.value.brandId) query.brand = filters.value.brandId
  if (filters.value.priceRange) query.price = filters.value.priceRange
  if (filters.value.sortBy !== 'default') query.sort = filters.value.sortBy
  if (searchKeyword.value) query.keyword = searchKeyword.value
  if (currentPage.value > 1) query.page = currentPage.value

  router.replace({ query })
}

const loadFromUrlQuery = () => {
  const query = route.query

  if (query.category) filters.value.categoryId = Number(query.category)
  if (query.brand) filters.value.brandId = Number(query.brand)
  if (query.price) filters.value.priceRange = query.price as string
  if (query.sort) filters.value.sortBy = query.sort as string
  if (query.keyword) searchKeyword.value = query.keyword as string
  if (query.page) currentPage.value = Number(query.page)
}

// 监听路由变化
watch(
  () => route.query,
  () => {
    loadFromUrlQuery()
    loadProducts()
  },
)

// 页面加载
onMounted(() => {
  loadFromUrlQuery()
  loadCategories()
  loadBrands()
  loadProducts()
})
</script>

<style scoped lang="scss">
.product-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .filter-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .filter-row {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 15px;

      .filter-group {
        display: flex;
        align-items: center;
        gap: 8px;

        .filter-label {
          font-weight: 500;
          color: #666;
          white-space: nowrap;
        }

        .filter-select {
          min-width: 120px;
        }
      }
    }

    .search-row {
      display: flex;
      gap: 10px;
      align-items: center;

      .search-input {
        flex: 1;
        max-width: 300px;
      }
    }
  }

  .products-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .page-title {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin: 0;
      }

      .result-count {
        color: #666;
        font-size: 14px;
      }
    }

    .products-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      min-height: 200px;
    }

    .empty-state {
      margin: 40px 0;
    }

    .pagination-section {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}

@media (max-width: 768px) {
  .product-list-container {
    padding: 10px;

    .filter-section {
      padding: 15px;

      .filter-row {
        flex-direction: column;
        gap: 10px;

        .filter-group {
          width: 100%;
        }
      }

      .search-row {
        flex-direction: column;
        align-items: stretch;

        .search-input {
          max-width: none;
        }
      }
    }

    .products-section {
      padding: 15px;

      .products-grid {
        grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
        gap: 15px;
      }
    }
  }
}
</style>
